//
//  MessageTableView.m
//  FlyingEagle
//
//  Created by SHkingwelan on 17/2/8.
//  Copyright © 2017年 lj. All rights reserved.
//

#import "MessageTableView.h"
#import "MessageTableViewCell.h"
#import "ChatDemoHelper.h"
#import "EaseUI.h"
#import "ContactDataObject.h"
#import <UserNotifications/UserNotifications.h>

#import "UIView+Additions.h"
#import "UIView+Placeholder.h"

#import "IMChatViewController.h"

#import "ChatInfoModel.h"


static NSString *const messageCell = @"MessageCell";

@interface MessageTableView()<UITableViewDelegate,UITableViewDataSource,TabelViewRefreshDelegate>
@property (strong, nonatomic) NSMutableArray *dataSourceArr;

@property (nonatomic, strong) NSMutableArray *nameArray;

@property (nonatomic, strong) NSIndexPath *chatIndex;


@end

@implementation MessageTableView

- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style{
    self = [super initWithFrame:frame style:style];
    if (self) {
        self.delegate = self;
        self.dataSource = self;
        self.refreshDelegate = self;
        self.tableFooterView = [UIView new];
//        self.backgroundColor = Main_BackColor;
        [ChatDemoHelper shareHelper].chatMessTableView = self;
        [self tableViewDidTriggerHeaderRefresh];
        self.rowHeight = 65;
        self.isRefresh = YES;
        [self endRefreshingWithNoMoreData];
    }
    return self;
}

- (NSMutableArray *)dataSourceArr {
    if (_dataSourceArr == nil) {
        _dataSourceArr = [[NSMutableArray alloc] initWithObjects:@[].mutableCopy,@[].mutableCopy, nil];
    }
    return _dataSourceArr;
}

- (void)setupUnreadArr {
    NSArray *arr = self.dataSourceArr[1];
    if (arr.count == 0) {
        [self tableViewDidTriggerHeaderRefresh];
    }
}

- (void)tableView:(UITableView *)tableView Refresh:(BOOL)refresh PageCount:(NSInteger)pageCount {
    [self tableViewDidTriggerHeaderRefresh];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataSourceArr[1] count];
//    return 5;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:messageCell];
    if (cell == nil) {
        cell = [[MessageTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:messageCell];
    }
    id<IConversationModel> model = self.dataSourceArr[1][indexPath.row];
    NSDictionary *dic = [[ContactDataObject shareInstance]queryEasemobuserid:model.conversation.conversationId];
//    cell.nameLabel.text = dic[@"userName"];
//    [self requestPostBH_User_getUserInfoByHxId:dic[@"userName"]];
    cell.nameLabel.text = self.nameArray[indexPath.row];
    cell.messageLabel.attributedText =  [[EaseEmotionEscape sharedInstance] attStringFromTextForChatting:[self _latestMessageTitleForConversationModel:model]textFont:cell.detailTextLabel.font];
//    cell.timeLabel.text = [self _latestMessageTimeForConversationModel:model];
//    [cell.headImage sd_setImageWithURL:[NSURL URLWithString:dic[@"logo"]] placeholderImage:[UIImage imageNamed:@"home_17"]];
    if (model.conversation.unreadMessagesCount == 0) {
        cell.messageNumberLabel.hidden = YES;
    }else {
        cell.messageNumberLabel.text = [NSString stringWithFormat:@"%ld",(long)model.conversation.unreadMessagesCount];
        cell.messageNumberLabel.hidden = NO;
    }
    
//    cell.messageNumberLabel.text = [NSString stringWithFormat:@"%ld", indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    EaseConversationModel *model = self.dataSourceArr[1][indexPath.row];
    self.chatIndex = indexPath;
    
    BOOL ifLoginOK = [EMClient sharedClient].isLoggedIn;
    SGUserModel *model1 = [SGUserInfo getUserInfo];
    if (ifLoginOK) {
        [self gotoChatAction:model];
    } else {
        [[EMClient sharedClient] loginWithUsername:model1.hx_user_name password:model1.hx_password completion:^(NSString *aUsername, EMError *aError) {
            if (aError == nil) {
                [self gotoChatAction:model];
            } else {
                [[BHAlertUtil alertManager] showPromptInfo:@"暂无聊天账号，重新登录试试～"];
            }
        }];
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        EaseConversationModel *model = self.dataSourceArr[1][indexPath.row];
        [[EMClient sharedClient].chatManager deleteConversation:model.conversation.conversationId isDeleteMessages:YES completion:nil];
        [self.dataSourceArr[1] removeObjectAtIndex:indexPath.row];
        [self deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60.0;
}

#pragma mark - HeaderRefresh
- (void)tableViewDidTriggerHeaderRefresh {
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSArray* sorted = [conversations sortedArrayUsingComparator:
                       ^(EMConversation *obj1, EMConversation* obj2){
                           EMMessage *message1 = [obj1 latestMessage];
                           EMMessage *message2 = [obj2 latestMessage];
                           if(message1.timestamp > message2.timestamp) {
                               return(NSComparisonResult)NSOrderedAscending;
                           }else {
                               return(NSComparisonResult)NSOrderedDescending;
                           }
                       }];
    
    NSMutableArray *mArr = self.dataSourceArr[1];
    [mArr removeAllObjects];
    for (EMConversation *converstion in sorted) {
        EaseConversationModel *model = nil;
        model = (EaseConversationModel*)[self modelForConversation:converstion];
//        NSDictionary *extDic = model.conversation.ext;
//        NSString *consId = model.conversation.conversationId;
//        NSDictionary *lastExtDic = model.conversation.latestMessage.ext;
        //NSLog(@"扩展字段:%@",lastExtDic);
        if (![BHSettingUtil dataAndStringIsNull:[self _latestMessageTitleForConversationModel:model]]) {
            [mArr addObject:model];
        }
        
//        NSDictionary *dic = [[ContactDataObject shareInstance]queryEasemobuserid:model.conversation.conversationId];
//        [self requestPostBH_User_getUserInfoByHxId:dic[@"userName"]];
    }
    
    self.nameArray = [NSMutableArray array];
    for (int i = 0; i < [self.dataSourceArr[1] count]; i++) {
        [self.nameArray addObject:@""];
        id<IConversationModel> model = self.dataSourceArr[1][i];
        NSDictionary *dic = [[ContactDataObject shareInstance]queryEasemobuserid:model.conversation.conversationId];
        [self requestPostBH_User_getUserInfoByHxId:dic[@"userName"] index:i];
    }
    
    [self reloadData];
    
//    if (mArr.count == 0) {
//        self.placeholderShow(YES);
//    } else {
//        self.placeholderShow(NO);
//    }
    [(AppDelegate *)[UIApplication sharedApplication].delegate setupUnreadMessageCount];
}

- (id<IConversationModel>)modelForConversation:(EMConversation *)conversation {
    EaseConversationModel *model = [[EaseConversationModel alloc] initWithConversation:conversation];
    return model;
}

#pragma mark - private
- (NSString *)_latestMessageTitleForConversationModel:(id<IConversationModel>)conversationModel
{
    NSString *latestMessageTitle = @"";
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];
    if (lastMessage) {
        EMMessageBody *messageBody = lastMessage.body;
        switch (messageBody.type) {
            case EMMessageBodyTypeImage:{
                latestMessageTitle = NSEaseLocalizedString(@"图片消息", @"[image]");
            } break;
            case EMMessageBodyTypeText:{
                NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                            convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                latestMessageTitle = didReceiveText;
            } break;
            case EMMessageBodyTypeVoice:{
                latestMessageTitle = NSEaseLocalizedString(@"音频消息", @"[voice]");
            } break;
            case EMMessageBodyTypeLocation: {
                latestMessageTitle = NSEaseLocalizedString(@"位置消息", @"[location]");
            } break;
            case EMMessageBodyTypeVideo: {
                latestMessageTitle = NSEaseLocalizedString(@"视频消息", @"[video]");
            } break;
            case EMMessageBodyTypeFile: {
                latestMessageTitle = NSEaseLocalizedString(@"[文件消息", @"[file]");
            } break;
            default: {
            } break;
        }
    }
    return latestMessageTitle;
}

- (NSString *)_latestMessageTimeForConversationModel:(id<IConversationModel>)conversationModel {
    NSString *latestMessageTime = @"";
    EMMessage *lastMessage = [conversationModel.conversation latestMessage];;
    if (lastMessage) {
        double timeInterval = lastMessage.timestamp ;
        if(timeInterval > 140000000000) {
            timeInterval = timeInterval / 1000;
        }
        NSDateFormatter* formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"YYYY-MM-dd HH:mm"];
        latestMessageTime = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timeInterval]];
    }
    return latestMessageTime;
}

- (void)sendMessageClick:(UIButton *)sender {

}

- (void)gotoChatAction:(EaseConversationModel *)model {
    if (![BHSettingUtil dataAndStringIsNull:model.conversation.conversationId]) {
        IMChatViewController *chatVC = [[IMChatViewController alloc] initWithConversationChatter:model.conversation.conversationId conversationType:EMConversationTypeChat];
        chatVC.title = self.nameArray[self.chatIndex.row];
        
        NSDictionary *dic = [[ContactDataObject shareInstance]queryEasemobuserid:model.conversation.conversationId];
//        NSDictionary *dic1 = @{@"easemobuserId":model.conversation.conversationId,@"userName":[BHSettingUtil dataAndStringIsNull:dic[@"userName"]]?@"":dic[@"userName"],@"logo":[BHSettingUtil dataAndStringIsNull:dic[@"logo"]]?@"":dic[@"logo"]};
        NSDictionary *dic1 = @{@"easemobuserId":model.conversation.conversationId,@"userName":self.nameArray[self.chatIndex.row],@"logo":[BHSettingUtil dataAndStringIsNull:dic[@"logo"]]?@"":dic[@"logo"]};

        [[ContactDataObject shareInstance]insertData:dic1];

        BaseViewController *viewController = [self baseViewController];
        [self tableViewDidTriggerHeaderRefresh];
        [viewController pushViewController:chatVC animated:YES];

//        viewController.hidesBottomBarWhenPushed = YES;
//        [viewController.navigationController pushViewController:chatVC animated:YES];
//        //修改tabBar的frame
//        CGRect frame = viewController.tabBarController.tabBar.frame;
//        frame.origin.y = App_Frame_Height - frame.size.height;
//        viewController.tabBarController.tabBar.frame = frame;
    } else {
        [[BHAlertUtil alertManager] showPromptInfo:@"sorry，对方无账号"];
    }
}

- (void)requestPostBH_User_getUserInfoByHxId:(NSString *)hx_name index:(NSInteger)index {
//    id<IConversationModel> model = self.dataSourceArr[1][indexPath.row];
//    NSDictionary *dic = [[ContactDataObject shareInstance]queryEasemobuserid:model.conversation.conversationId];

    
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:hx_name forKey:@"hx_user_name"];
    [PPHTTPRequest requestPostBH_User_getUserInfoByHxId:^(id response, BOOL success) {
        if (success) {
//            return @"llllll";
            ChatInfoModel *model = [ChatInfoModel yy_modelWithJSON:response];
//            NSLog(model);
            [self.nameArray replaceObjectAtIndex:index withObject:model.company_info.company_name];
            [self reloadData];
        }else {
//            return @"00000";
        }
    } params:params];
    
    
}


@end
